package pe.edu.upc.dsd.l33t.dao.jdbc;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;

import pe.edu.upc.dsd.l33t.dao.BookDao;
import pe.edu.upc.dsd.l33t.model.Book;

@Repository
public class BookDaoJdbc extends SimpleJdbcDaoSupport implements BookDao {
	
	@Autowired
	public BookDaoJdbc(DataSource dataSource) {
		setDataSource(dataSource);
	}

	@Override
	public Book find(String isbn) {
		
		try {
			return getSimpleJdbcTemplate()
					.queryForObject(
							"SELECT isbn, title, author, description, year, pages, price, imageUrl, bookUrl FROM books WHERE isbn=?",
							new BeanPropertyRowMapper<Book>(Book.class),
							isbn);
		} catch (EmptyResultDataAccessException e) {
			System.out.println(e.getMessage());
			return null;
		}
	}

	@Override
	public List<Book> findAll() {

		try {
			return getSimpleJdbcTemplate().query(
					"SELECT isbn, title, author, description, year, pages, price, imageUrl, bookUrl FROM books",
					new BeanPropertyRowMapper<Book>(Book.class));
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return null;
		}
		
	}

	@Override
	public void save(Book book) {
		getSimpleJdbcTemplate()
		.update("insert into books(isbn,title,author,description,year,pages,price,imageUrl,bookUrl)  values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
				book.getIsbn(),book.getTitle(),book.getAuthor(),book.getDescription(),book.getYear(),book.getPages(),
				book.getPrice(),book.getImageUrl(),book.getBookUrl());
		
	}
	
	@Override
	public void update(Book book) {
		getSimpleJdbcTemplate().update(
				"update books set title=?, author=?, description=?, year=?, pages=?, price=?,imageUrl=?,bookUrl=? where isbn=?",
				book.getTitle(), book.getAuthor(), book.getDescription(), book.getYear(), book.getPages() ,book.getPrice(),book.getImageUrl(),book.getBookUrl(), book.getIsbn());
	}

	@Override
	public void delete(Book book) {
		getSimpleJdbcTemplate().update("delete from books where isbn=?",
				book.getIsbn());
	}

}
